package com.xhl.consul.tool.controller;

import cn.hutool.crypto.SecureUtil;
import com.xhl.common.util.MakeRSAUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

/**
 * 非对称加密RSA算法测试
 * @Author CazCen
 * @Date 2021/11/29 14:29
 */
@Api(tags = "RSA非对称算法测试")
@RestController
@RequestMapping("/test/rsa")
@Slf4j
public class RSAController {

    public String myKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr5OgTq+vQOKbjQhtivaUSOm0YZ8BA0GVHroITVrLqa4EIS1S3e6YSnZ3S0UIlzJCni/nzQ9YCC8DxYhCtmdnOUOC7wsrKXMBVRpTI6A/WL8lj9Pr4zXEaAhmhb+3W7dJYOBnmV9ky3i6bfqN1S7mGVCxNd4JAdrn7SRw8JYfl+aBAX56XgoXB0Q1N3zIr8PIrmL85ZFN6V00QwY3fCnorhG/UirgCPMdeXzoR7Z/8x8UHeeuHqZQ2SVMliIER5VWXN+rgavNtvHPy9T2UgjuYzJp0XkjYaFpXhIbQzTgwrQuP73pwlAQOfOPfgXdGQXqnFkrggaQZz7+vc2QZzHY/QIDAQAB";

    @PostMapping("/rsa")
    @ApiOperation("RSA非对称算法测试-1")
    private void RsaTest() throws  Exception{

        // 生成私钥
        byte[] privateKeyEncoded = MakeRSAUtil.getPrivateKeyEncoded("123456".getBytes("UTF-8"));
        log.info("生成私钥 privateKeyEncoded:{}",privateKeyEncoded);
        log.info("生成私钥 privateKeyString:{}",new String(privateKeyEncoded,"UTF-8"));

        // 生成公钥
        byte[] publicKeyEncoded = MakeRSAUtil.getPublicKeyEncoded(myKey.getBytes());
        log.info("生成公钥:{}",publicKeyEncoded);



        String data = "123456789!@";

        //使用公钥加密数据
        byte[] dataBytes = MakeRSAUtil.encryptByPublicKey(data.getBytes(), publicKeyEncoded);
        log.info("加密后的数据:{}",dataBytes);
        log.info("加密后的数据:{}",new String(dataBytes));

        // 使用私钥解密
        byte[] bytes = MakeRSAUtil.decryptByPrivateKey(dataBytes, privateKeyEncoded);
        log.info("解密后的数据:{}",dataBytes);
        log.info("解密后的数据:{}",new String(dataBytes));

    }


    @PostMapping("/rsa2")
    @ApiOperation("generateKeyPair:非对称算法测试-2")
    private void RsaTest2() throws  Exception{

        KeyPair keyPair = MakeRSAUtil.getKeyPair();
        // 生成公钥
        PublicKey aPublic = keyPair.getPublic();

        // 生成私钥
        PrivateKey aPrivate = keyPair.getPrivate();

        String data = "123456789!@";

        //使用公钥加密数据
        byte[] dataBytes = MakeRSAUtil.encryptByPublicKey(data.getBytes(), aPublic.getEncoded());
        log.info("加密后的数据:{}",dataBytes);
        log.info("加密后的数据:{}",new String(dataBytes));

        // 使用私钥解密
        byte[] bytes = MakeRSAUtil.decryptByPrivateKey(dataBytes, aPrivate.getEncoded());
        log.info("解密后的数据:{}",bytes);
        log.info("解密后的数据:{}",new String(bytes));

    }


}
